package cn.com.api.controller;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.api.entity.ApiU_juhe_region;
import cn.com.api.service.ApiU_juhe_regionService;
import cn.com.juhe.JuheConfig;
import cn.com.util.JsonUtil;
import cn.com.util.Util;
import cn.com.util.Utils;

@Controller
@RequestMapping(Utils.SYS_API + "JuHe/")
public class ApiJuHeController {
	public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
    
    @Autowired
    public ApiU_juhe_regionService apiU_juhe_regionService;
    
    private static Logger logger = Logger.getLogger(ApiMemberController.class);
    
    //同步聚合数据的区域编码
    @Transactional
	@RequestMapping(value = "UpdateJuHeRegion")
	public void UpdateJuHeRegion(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	Map<String, Object> map = new HashMap<String, Object>();
    	String result =null;
    	String url ="http://v.juhe.cn/xiangji_weather/areaList.php";//请求接口地址
    	Map params = new HashMap();//请求参数
    	params.put("key",JuheConfig.city_App_Key);//应用APPKEY(应用详细页查询)
       try {
	       result =net(url, params, "GET");
	       JSONObject object = JSONObject.fromObject(result);
	       if(object.getInt("error_code")==0){
	           System.out.println(object.get("result"));
	           JSONArray area_list = object.getJSONArray("result");
	           
	           List<ApiU_juhe_region> juhe_region_list = new ArrayList<ApiU_juhe_region>();
	           
	           Iterator<Object> it = area_list.iterator();
	           while (it.hasNext()) {
	                JSONObject ob = (JSONObject) it.next();
	                ApiU_juhe_region juhe_region = new ApiU_juhe_region();
	                if(ob.getString("areaid")!=null){
//	                	 "province": "北京",
//	                     "city": "北京",
//	                     "area": "北京",
//	                     "areaid": "101010100",
//	                     "lon": "116.4",
//	                     "lat": "39.9"
	                	juhe_region.setArea(ob.getString("area"));
	                	juhe_region.setAreaid(ob.getString("areaid"));
	                	juhe_region.setCity(ob.getString("city"));
	                	juhe_region.setProvince(ob.getString("province"));
	                	juhe_region.setLat(ob.getString("lat"));
	                	juhe_region.setLon(ob.getString("lon"));
	                	juhe_region_list.add(juhe_region);
	                }
	            }
				this.apiU_juhe_regionService.Update_Juhe_Region(juhe_region_list);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "更新成功！");
	       }else{
	           System.out.println(object.get("error_code")+":"+object.get("reason"));
	           map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
	           map.put(Utils.MESSAGE, "更新失败！");
	       }
	   } catch (Exception e) {
		   e.printStackTrace();
		   logger.error(Util.getStackTraceAsString(e));
		   map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
		   map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
    	 
    }
    
    //根据省市区获取区域ID
	@Transactional
	@RequestMapping(value = "getAreaID")
	public void getAreaID(HttpServletRequest request, HttpServletResponse response, 
			String province, String city, String area) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> params = new HashMap<String, String>();
	   try {

				params.put("province", province);
				params.put("city", city);
				params.put("area", area);
		   		String area_id = this.apiU_juhe_regionService.getAreaID(params);
		   		
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "获取成功！");
				map.put("areaid", area_id);

	   } catch (Exception e) {
		   e.printStackTrace();
		   logger.error(Util.getStackTraceAsString(e));
		   map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
		   map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
		 
	}
    
//    //配置您申请的KEY
//    public static final String APPKEY ="*************************";
// 
//    //1.银行卡实名认证查询
//    public static void getRequest1(){
//        String result =null;
//        String url ="http://v.juhe.cn/verifybankcard/query";//请求接口地址
//        Map params = new HashMap();//请求参数
//            params.put("bankcard","");//银行卡卡号
//            params.put("realname","");//姓名(需utf8编码的urlencode)
//            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
// 
//        try {
//            result =net(url, params, "GET");
//            JSONObject object = JSONObject.fromObject(result);
//            if(object.getInt("error_code")==0){
//                System.out.println(object.get("result"));
//            }else{
//                System.out.println(object.get("error_code")+":"+object.get("reason"));
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
    
    /**
    *
    * @param strUrl 请求地址
    * @param params 请求参数
    * @param method 请求方法
    * @return  网络请求字符串
    * @throws Exception
    */
   public static String net(String strUrl, Map params,String method) throws Exception {
       HttpURLConnection conn = null;
       BufferedReader reader = null;
       String rs = null;
       try {
           StringBuffer sb = new StringBuffer();
           if(method==null || method.equals("GET")){
               strUrl = strUrl+"?"+urlencode(params);
           }
           URL url = new URL(strUrl);
           conn = (HttpURLConnection) url.openConnection();
           if(method==null || method.equals("GET")){
               conn.setRequestMethod("GET");
           }else{
               conn.setRequestMethod("POST");
               conn.setDoOutput(true);
           }
           conn.setRequestProperty("User-agent", userAgent);
           conn.setUseCaches(false);
           conn.setConnectTimeout(DEF_CONN_TIMEOUT);
           conn.setReadTimeout(DEF_READ_TIMEOUT);
           conn.setInstanceFollowRedirects(false);
           conn.connect();
           if (params!= null && method.equals("POST")) {
               try {
                   DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                       out.writeBytes(urlencode(params));
               } catch (Exception e) {
                   // TODO: handle exception
               }
           }
           InputStream is = conn.getInputStream();
           reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
           String strRead = null;
           while ((strRead = reader.readLine()) != null) {
               sb.append(strRead);
           }
           rs = sb.toString();
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           if (reader != null) {
               reader.close();
           }
           if (conn != null) {
               conn.disconnect();
           }
       }
       return rs;
   }

   //将map型转为请求参数型
   public static String urlencode(Map<String,Object>data) {
       StringBuilder sb = new StringBuilder();
       for (Map.Entry i : data.entrySet()) {
           try {
               sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
           } catch (UnsupportedEncodingException e) {
               e.printStackTrace();
           }
       }
       return sb.toString();
   }
}
